package ${package}.dao;

import ${package}.model.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 * UserDao implementation.
 */
@Repository
public class UserDaoImpl implements UserDao {
    /**
     * Dao logger.
     */
    private Log logger = LogFactory.getLog(this.getClass());

    /**
     * JPA persistence context.
     */
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * Dao info string.
     */
    public static final String DAO_INFO = UserDaoImpl.class.getName() + ", $Revision: $";


    @Override
    public String getDaoInfo() {
        logger.debug(UserDaoImpl.class.getName() + " Info requested.");

        return DAO_INFO;
    }

    @Override
    public void save(final User user) {
        logger.debug("Persisting user: " + user.getUsername());
        entityManager.persist(user);
    }

    @Override
    public void delete(final User user) {
        logger.debug("Removing user: " + user.getUsername());
        entityManager.remove(user);
    }

    @Override
    public User getByUsername(final String username) {
        logger.debug("Retrieving user: " + username);

        User u = null;
        try {
            u = (User) entityManager.createQuery(
                    "SELECT u FROM User u WHERE u.username = :username").setParameter("username", username).getSingleResult();
        } catch (NoResultException e) {
            logger.debug("no user found: " + username);
        }

        return u;
    }
}
